package cn.hongsw.taskschedule.service.impl;

import cn.hongsw.taskschedule.mapper.DataSourceInfoMapper;
import cn.hongsw.taskschedule.model.DataSourceInfo;
import cn.hongsw.taskschedule.service.DataSourceInfoService;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @author :hongsw
 * @date :2021-05-19 14:21
 */
@Service
@Slf4j
public class DataSourceInfoServiceImpl extends ServiceImpl<DataSourceInfoMapper, DataSourceInfo> implements DataSourceInfoService {
    @Resource(name = "basicDataSourceCreator")
    private DataSourceCreator dataSourceCreator;
    @Resource
    private DataSource dataSource;

    /**
     * 新增数据源
     *
     * @param dataSourceInfo 数据源信息
     * @return boolean
     * @author hongsw
     * @date 2021/5/19 14:22
     **/
    @Override
    public boolean addDataSource(DataSourceInfo dataSourceInfo) {
        if (!this.save(dataSourceInfo)) {
            log.error("{}，数据库保存失败", dataSourceInfo.getName());
            return false;
        }
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        if (ds.getCurrentDataSources().containsKey(String.valueOf(dataSourceInfo.getId()))) {
            log.error("数据源中已有{}的数据源", dataSourceInfo.getId());
            return false;
        }
        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        dataSourceProperty.setDriverClassName(dataSourceInfo.getDriverClassName());
        dataSourceProperty.setUrl(dataSourceInfo.getUrl());
        dataSourceProperty.setUsername(dataSourceInfo.getUsername());
        dataSourceProperty.setPassword(dataSourceInfo.getPassword());
        dataSourceProperty.setType(DruidDataSource.class);
        dataSourceProperty.setPoolName(String.valueOf(dataSourceInfo.getId()));
        DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
        ds.addDataSource(dataSourceProperty.getPoolName(), dataSource);
        return true;
    }

    /**
     * 删除数据源
     *
     * @param id 数据源id
     * @return boolean
     * @author hongsw
     * @date 2021/5/19 17:18
     **/
    @Override
    public boolean deleteDataSource(Long id) {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        ds.removeDataSource(String.valueOf(id));
        return this.removeById(id);
    }
}
